"""
移动端驱动器基类
定义统一的接口，供所有具体实现继承
"""

import time
from abc import ABC, abstractmethod
from typing import Optional, Dict, Any


class MobileDriverBase(ABC):
    """移动端驱动器基类"""

    @abstractmethod
    def init_device(self) -> None:
        """初始化设备连接"""
        pass

    @abstractmethod
    def start_app(self, package_name: Optional[str] = None) -> bool:
        """启动App"""
        pass

    @abstractmethod
    def stop_app(self, package_name: Optional[str] = None) -> bool:
        """停止App"""
        pass

    @abstractmethod
    def click_coordinate(self, x: int, y: int) -> bool:
        """点击坐标"""
        pass

    @abstractmethod
    def click_text(self, text: str, timeout: int = 5) -> bool:
        """点击包含指定文本的元素"""
        pass

    @abstractmethod
    def wait_for_text(self, text: str, timeout: int = 10) -> bool:
        """等待文本出现"""
        pass

    @abstractmethod
    def input_text(self, text_content: str) -> bool:
        """输入文本"""
        pass

    @abstractmethod
    def swipe_screen(
        self, start_x: int, start_y: int, end_x: int, end_y: int, duration: float = 0.5
    ) -> bool:
        """滑动屏幕"""
        pass

    @abstractmethod
    def press_key(self, key: str) -> bool:
        """按键操作"""
        pass

    @abstractmethod
    def press_back(self) -> bool:
        """按返回键"""
        pass

    @abstractmethod
    def press_home(self) -> bool:
        """按Home键"""
        pass

    @abstractmethod
    def screenshot(self, filename: Optional[str] = None) -> str:
        """截图"""
        pass

    @abstractmethod
    def is_app_running(self, package_name: Optional[str] = None) -> bool:
        """检查App是否运行"""
        pass

    @abstractmethod
    def close_device(self) -> None:
        """关闭设备连接"""
        pass

    # 兼容性接口
    def find_element(self, **kwargs) -> bool:
        """查找元素（兼容接口）"""
        if "text" in kwargs:
            return self.wait_for_text(kwargs["text"], timeout=2)
        elif "textContains" in kwargs:
            return self.wait_for_text(kwargs["textContains"], timeout=2)
        return False

    def find_elements(self, **kwargs) -> list:
        """查找多个元素（兼容接口）"""
        # 简化实现，返回空列表
        return []

    def scroll_to_element(self, **kwargs) -> bool:
        """滚动到元素（兼容接口）"""
        if "textContains" in kwargs:
            return self.scroll_to_find_text(kwargs["textContains"])
        elif "text" in kwargs:
            return self.scroll_to_find_text(kwargs["text"])
        return False

    def scroll_to_find_text(self, text: str, max_scrolls: int = 5) -> bool:
        """滚动查找文本（基础实现）"""
        for i in range(max_scrolls):
            if self.wait_for_text(text, timeout=2):
                return True
            # 向下滚动
            self.swipe_screen(540, 1500, 540, 800)  # 默认分辨率的滚动
            time.sleep(1)
        return False

    def click_element(self, timeout: int = 10, **kwargs) -> bool:
        """点击元素（兼容接口）"""
        if "text" in kwargs:
            return self.click_text(kwargs["text"], timeout)
        elif "textContains" in kwargs:
            return self.click_text(kwargs["textContains"], timeout)
        return False

    def wait_for_element(self, timeout: int = 10, **kwargs) -> bool:
        """等待元素出现（兼容接口）"""
        return self.find_element(**kwargs)

    def tap_coordinate(self, x: int, y: int) -> None:
        """点击坐标（兼容接口）"""
        self.click_coordinate(x, y)

    def get_text(self, **kwargs) -> str:
        """获取元素文本（兼容接口）"""
        return ""

    def swipe(
        self, fx: float, fy: float, tx: float, ty: float, duration: float = 0.5
    ) -> None:
        """滑动操作（兼容接口）"""
        # 默认使用1080x1920分辨率转换
        width, height = 1080, 1920
        start_x = int(fx * width)
        start_y = int(fy * height)
        end_x = int(tx * width)
        end_y = int(ty * height)
        self.swipe_screen(start_x, start_y, end_x, end_y, duration)
